<template>
  <div class="space-y-6 max-w-2xl">
    <h2 class="text-xl font-semibold text-gray-800">设置</h2>

    <!-- AI 配置 -->
    <div class="bg-white rounded-lg shadow p-6">
      <h3 class="text-lg font-medium mb-4">AI 配置</h3>
      
      <div class="space-y-4">
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">SiliconFlow API Key</label>
          <input
            v-model="config.siliconFlowAPIKey"
            type="password"
            class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
            placeholder="请输入 SiliconFlow API Key"
          />
          <p class="mt-1 text-xs text-gray-500">
            获取 API Key：<a href="https://siliconflow.cn" target="_blank" class="text-blue-600 hover:underline">https://siliconflow.cn</a>
          </p>
        </div>
        
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">OCR 模型</label>
          <div class="flex gap-2">
            <select
              v-model="config.ocrModelID"
              class="flex-1 px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              <option value="">请选择模型</option>
              <option v-for="model in models" :key="model.id" :value="model.id">
                {{ model.name }}
              </option>
            </select>
            <button
              @click="loadModels"
              :disabled="loadingModels"
              class="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 disabled:bg-gray-300 disabled:cursor-not-allowed"
            >
              {{ loadingModels ? '加载中...' : '刷新' }}
            </button>
          </div>
          <p class="mt-1 text-xs text-gray-500">
            选择用于 OCR 识别的模型
          </p>
        </div>
        
        <div class="bg-blue-50 border border-blue-200 rounded-lg p-3">
          <p class="text-sm text-blue-800">
            <strong>提示：</strong>配置 API Key 后，点击"刷新"按钮加载可用的模型列表。
          </p>
        </div>
      </div>
    </div>

    <!-- 模板文件夹配置 -->
    <div class="bg-white rounded-lg shadow p-6">
      <h3 class="text-lg font-medium mb-4">模板文件夹</h3>
      
      <div class="space-y-4">
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">模板文件夹路径</label>
          <div class="flex gap-2">
            <input
              v-model="config.templatesFolder"
              type="text"
              readonly
              class="flex-1 px-3 py-2 border border-gray-300 rounded-lg bg-gray-50"
              placeholder="未设置"
            />
            <button
              @click="selectTemplatesFolder"
              class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600"
            >
              选择文件夹
            </button>
          </div>
          <p class="mt-1 text-xs text-gray-500">
            选择包含模板文件的文件夹，软件启动时会自动加载该文件夹中的模板
          </p>
        </div>
        
        <div v-if="config.templatesFolder" class="bg-green-50 border border-green-200 rounded-lg p-3">
          <p class="text-sm text-green-800">
            <strong>当前路径：</strong>{{ config.templatesFolder }}
          </p>
        </div>
      </div>
    </div>

    <!-- 保存按钮 -->
    <div class="flex justify-end">
      <button
        @click="saveConfig"
        :disabled="saving"
        class="px-6 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 disabled:bg-gray-400 disabled:cursor-not-allowed"
      >
        {{ saving ? '保存中...' : '保存配置' }}
      </button>
    </div>

    <!-- 关于 -->
    <div class="bg-white rounded-lg shadow p-6">
      <h3 class="text-lg font-medium mb-4">关于</h3>
      <div class="space-y-2 text-sm text-gray-600">
        <p><strong>版本：</strong>1.0.0</p>
        <p><strong>功能：</strong>批量生成文书工具，支持模板管理和 OCR 自动填充</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { configAPI, ocrAPI, templateAPI } from '../api/app.js'

const config = ref({
  siliconFlowAPIKey: '',
  ocrModelID: '',
  templatesFolder: '',
})

const models = ref([])
const loadingModels = ref(false)
const saving = ref(false)

const loadConfig = async () => {
  try {
    const savedConfig = await configAPI.get()
    config.value = savedConfig
    
    // 如果已有 API Key，加载模型列表
    if (savedConfig.siliconFlowAPIKey) {
      await loadModels()
    }
  } catch (error) {
    console.error('加载配置失败:', error)
  }
}

const loadModels = async () => {
  if (!config.value.siliconFlowAPIKey) {
    alert('请先输入 API Key')
    return
  }
  
  loadingModels.value = true
  try {
    // 设置 API Key
    await ocrAPI.setSiliconFlowAPIKey(config.value.siliconFlowAPIKey)
    // 获取模型列表
    models.value = await ocrAPI.getSiliconFlowModels()
    
    // 如果已保存的模型在列表中，保持选中
    if (config.value.ocrModelID && !models.value.find(m => m.id === config.value.ocrModelID)) {
      // 如果保存的模型不在列表中，清空选择
      config.value.ocrModelID = ''
    }
  } catch (error) {
    console.error('加载模型失败:', error)
    alert('加载模型失败: ' + error.message)
  } finally {
    loadingModels.value = false
  }
}

const selectTemplatesFolder = async () => {
  try {
    const folderPath = await templateAPI.selectFolder()
    if (folderPath) {
      config.value.templatesFolder = folderPath
    }
  } catch (error) {
    console.error('选择文件夹失败:', error)
    alert('选择文件夹失败: ' + error.message)
  }
}

const saveConfig = async () => {
  saving.value = true
  try {
    await configAPI.save(config.value)
    
    // 如果设置了模板文件夹，自动导入模板
    if (config.value.templatesFolder) {
      try {
        await templateAPI.importFromFolder(config.value.templatesFolder)
      } catch (error) {
        console.error('导入模板失败:', error)
        // 不阻止保存配置，只记录错误
      }
    }
    
    alert('配置已保存')
  } catch (error) {
    console.error('保存配置失败:', error)
    alert('保存配置失败: ' + error.message)
  } finally {
    saving.value = false
  }
}

onMounted(() => {
  loadConfig()
})
</script>
